package com.dingdang.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dingdang.data.Result;
import com.dingdang.dto.CarGoodsDTO;
import com.dingdang.dto.OrderDetailsDTO;
import com.dingdang.dto.UserDTO;
import com.dingdang.em.ResultEnum;
import com.dingdang.entity.TbFenqi;
import com.dingdang.feign.ReserveFeign;
import com.dingdang.mapper.TbFenqiMapper;
import com.dingdang.utils.IdWorker;
import com.dingdang.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.List;


@RestController
@RequestMapping("fenqiCon")
@Api("分期付款服务接口")
public class FenQiController
{

    @Autowired
    private TbFenqiMapper fenqiMapper;

    @Autowired
    private ReserveFeign reserveFeign;

    @Autowired
    private TimeController timeController;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping
    @ApiImplicitParams
    ({
            @ApiImplicitParam(name = "CarGoodsDTO",value = "车辆详情实体类",required = true,paramType = "body"),
    })
    private Result CreateFenQiOrder(@RequestBody CarGoodsDTO carGoodsDTO, HttpServletRequest request)
    {

        String token = request.getHeader("authToken");
        //获取登录态
        Claims authToken = jwtUtil.parseJwt(token);
        String subject = authToken.getSubject();
        UserDTO userDTO = JSONObject.parseObject(subject, UserDTO.class);
        //用户id
        Long uid = userDTO.getUid();
        //用户手机号
        String phone = userDTO.getPhone();



        //获取总金额
        Double carCount = Double.valueOf(carGoodsDTO.getCarCount());
        double carCount2 = carCount - 2000D;
        //获取首付
        double downPayments = carCount2 * 0.7;

        /**
         * 期数：12期、24期、36期
         * 年化率：12期（3.16%）、24期（4.17%）、36期（5.18%
         * */

        Long fen = carGoodsDTO.getFenQi();
        //获取年化率
        Double nianHuaLv = 0D;
        if (fen == 12)
        {
            nianHuaLv =3.16;
        }
        else if (fen == 24)
        {
            nianHuaLv = 4.17;
        }
        else if (fen == 36)
        {
            nianHuaLv = 5.18;
        }



        //将 分期数,
        //[（分期车辆的总价-首付价）*年化率]/期数
        //本期实付金额
        OrderDetailsDTO orderDetailsDTO = new OrderDetailsDTO();
        //每月应还金额

        BigDecimal ammont = BigDecimal.valueOf(((carCount2 - downPayments) * nianHuaLv) / fen);
        orderDetailsDTO.setPayment(ammont).
                //carId
                setCarId(carGoodsDTO.getCarId().toString()).
                //卖家名
                setSellerName(carGoodsDTO.getSellerName()).
                //支付类型
                setPaymentType("2").
                //收车人地区名称
                setReceiverAreaName(orderDetailsDTO.getReceiverAreaName()).
                //手机号
                setReceiverMobile(phone);
        //用户在选择分期付款后调取订单号  调用订单接口
        //reverseFeign.createOrder(orderDetailsDTO);

        //增加分期表信息
        TbFenqi fenqi = new TbFenqi();
        long fenqiId = new IdWorker().nextId();
        fenqi.setId(fenqiId)
                .setFenqiUserId(uid)
                .setFenqiFenqishu(carGoodsDTO.getFenQi()).
                setFenqiAmmont(ammont).
                setFenqiTotalAmmont(BigDecimal.valueOf(carCount2)).
                setFenqiFenqishuRemaining(carGoodsDTO.getFenQi())
                .setFenqiPhone(phone);


        try
        {
            //增加到分期表
            LambdaQueryWrapper<TbFenqi> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TbFenqi::getFenqiPhone,phone);
            List<TbFenqi> fenqiList = fenqiMapper.selectList(wrapper);
            //如果查询无结果则返回则增加分期表
            if(fenqiList.size()<=0)
            {
                fenqiMapper.insert(fenqi);
            }
            orderDetailsDTO.setToken(token);
            //生成订单
            Result order = reserveFeign.createOrder(orderDetailsDTO);
            System.out.println(order.getData());
            //付款
            reserveFeign.OrderPay((String) order.getData(),"2000","定金","123");

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return Result.response(ResultEnum.SUCCESS);
    }

}
